$(document).ready(function(){
    var cache = {};
    function showSelectTags(tags) {
        $(".tags-autocomplete-select-menu").html("");
        $(".tags-autocomplete-select-menu").fadeIn();
        var opt = "";
        $.each(tags, function(i, event) {
            var tagList = $('#submit-tags').val().split(",");
            if (tagList.indexOf(tags[i]) == -1) {
                opt += "<div class=\"tags-autocomplete-select-item\" data-value=\""+ tags[i] +"\">" + tags[i] +"</div>";
            }
        });
        $(".tags-autocomplete-select-menu").html(opt);
    }
    function searchTags(word) {
        if ( word in cache ) {
            showSelectTags(cache[ word ]);
        } else {
            $.getJSON("/api/tags/search",{q: word},function(json) {
                if (json.code == 200) {
                    cache[ word ] = json.data;
                    showSelectTags(json.data);
                }
            });
        }
    }
    function insertShowTags(tags) {
        $.each(tags, function(i, event) {
            if (tags[i].length != 0) {
                var opt = "<a class=\"label-item\">" + tags[i] + "<i class=\"icon-delete\"></i></a>";
                $("#input-tags").before(opt);
            }
        });
    }

    function updateSubmitTags() {
        var tagsList = "";
        $("a.label-item").each(function(){
            if (tagsList.length == 0) {
                tagsList = $(this).text();
            } else {
                tagsList += "," + $(this).text();
            }
        });
        $('#submit-tags').val(tagsList);
    }
    function insertTags(insertTag) {
        var tags = insertTag.split(",");
        insertShowTags(tags);

        /* 清空输入框内容 */
        $("#input-tags").val("");

        /* 插入tag到隐藏的input框 */
        updateSubmitTags();
    }

    function initShowTags() {
        var tags = $('#submit-tags').val().split(",");
        insertShowTags(tags);
    }
    initShowTags();

    $("#input-tags").focus(function(){
        searchTags($(this).val().replace(/(^\s*)|(\s*$)/g, ""));
    });
    $("#input-tags").blur(function(){
        $(".tags-autocomplete-select-menu").fadeOut();
    });
    $("#input-tags").bind('input propertychange',function(e){
        searchTags($(this).val().replace(/(^\s*)|(\s*$)/g, ""));
        var word = $(this).val();
        var pos = word.indexOf(",");
        if (pos > 0) {
            insertTags(word);
        }
    });

    $(document).on("click",".tags-autocomplete-select-item",function() {
        insertTags($(this).attr("data-value"));
    });
    $(document).on("click",".icon-delete",function() {
        $(this).parent().remove();
        updateSubmitTags();
    });

});